package org.linuxsogood.boot.misc;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * @author wu.jiaran
 * @since 2020/11/16 9:44
 */
public class EmailSendUtil {

    private static Logger logger = LoggerFactory.getLogger(EmailSendUtil.class);
    private static String mailSenderUsername = "gm100861@126.com";
    private static String mailSenderPassword = "jiaxxx8";

    public static void main(String[] args) throws UnsupportedEncodingException {
        List<InternetAddress> mailTo = new ArrayList<>();
        mailTo.add(new InternetAddress("304958698@qq.com", "honway.liu", "UTF-8"));

        List<InternetAddress> mailCc = new ArrayList<>();
        mailCc.add(new InternetAddress("306417609@qq.com", "jiaran.wu", "UTF-8"));
        String subject = "Java邮件发送案例";
        String mailContent = "使用JAVA Mail发送邮件";
        String attachmentFilePath = "C:\\Users\\liu.hongwei\\Desktop\\机器人视频监控.md";

        send(mailTo, mailCc, subject, mailContent, attachmentFilePath);
    }

    /**
     * 发送邮件
     * @param mailTo 收件人列表 三个参数分别为: 邮箱, 显示的昵称(只用于显示, 没有特别的要求), 昵称的字符集编码
     * @param mailCc 抄送人列表
     * @param subject 邮件主题
     * @param mailContent 邮件正文
     * @param attachmentFilePath 附件文件的路径
     * @return 成功返回true
     */
    public static boolean send(List<InternetAddress> mailTo, List<InternetAddress> mailCc, String subject, String mailContent, String attachmentFilePath) {
        logger.info("sendMail ---- start");
        try {
            //1.创建邮件对象
            Properties properties = new Properties();
            properties.put("mail.transport.protocol", "smtp");
            properties.put("mail.smtp.host", "smtp.126.com");
            properties.put("mail.smtp.auth", "true");
            properties.put("mail.debug", "true");
            Session session = Session.getInstance(properties);
            MimeMessage mimeMessage =new MimeMessage(session);
            // 设置发件人信息，邮件地址，昵称，编码
            mimeMessage.setFrom(new InternetAddress(mailSenderUsername, "Honway", "UTF-8"));

            /*2.设置发件人
             * 其中 InternetAddress 的三个参数分别为: 邮箱, 显示的昵称(只用于显示, 没有特别的要求), 昵称的字符集编码
             * */


            /*3.设置收件人
            To收件人   CC 抄送  BCC密送*/
            if (CollectionUtils.isEmpty(mailTo)) {
                return true;
            }

            for (InternetAddress address : mailTo) {
                mimeMessage.addRecipient(MimeMessage.RecipientType.TO, address);
            }
            if (!CollectionUtils.isEmpty(mailCc)) {
                for (InternetAddress ccAddress : mailCc) {
                    mimeMessage.addRecipient(MimeMessage.RecipientType.CC, ccAddress);
                }
            }

            /*4.设置标题和内容*/
            mimeMessage.setSubject(subject,"UTF-8");

            //一个Multipart对象包含一个或多个bodypart对象，组成邮件正文
            MimeMultipart multipart = new MimeMultipart();


            //创建文本节点
            if (StringUtils.isNotEmpty(mailContent)) {
                MimeBodyPart text = new MimeBodyPart();
                text.setContent(mailContent,"text/html;charset=UTF-8");
                //将文本和图片添加到multipart
                multipart.addBodyPart(text);
            }

            //创建附件节点  读取本地文件,并读取附件名称
            if (StringUtils.isNotBlank(attachmentFilePath)) {
                MimeBodyPart file1 = new MimeBodyPart();
                DataHandler dataHandler2 = new DataHandler(new FileDataSource(attachmentFilePath));
                file1.setDataHandler(dataHandler2);
                file1.setFileName(MimeUtility.encodeText(dataHandler2.getName()));
                multipart.addBodyPart(file1);
                //关联关系
                multipart.setSubType("mixed");
            }


            mimeMessage.setContent(multipart);

            mimeMessage.setSentDate(new Date());
            mimeMessage.saveChanges();

            //获取邮件传输对象
            Transport transport = session.getTransport("smtp");
            transport.connect(mailSenderUsername, mailSenderPassword);
            transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
            transport.close();

            logger.info("sendMail  -----end");
            return true;
        } catch (Exception e) {
            logger.error("发送邮件异常", e);
        }
        return false;
    }

}
